rendezvous with cassidoo issue #147 challenge
Given a number n, return the number of 1s in the binary representation of n
by Jesse Rogers
HTML
<div class="wrapper">
<h1>How Many 1's?</h1>
<p>How much junk your number got in its binary trunk? Let's find out.</p>
<div class="input-wrap">
<label for="numberInput">Enter number</label>
<input placeholder="Choose your fighter" type="number" id="numberInput" name="numberInput">
<button id="btn">Run</button>
</div>
<div class="result">
<span>Number of 1's: </span>
<code id="resultText"></code>
</div>
</div>
CSS
html,
body {
font-size: 24px;
margin: 0;
padding: 0;
}
* {
box-sizing: border-box;
font-family: monospace;
}
.wrapper {
padding: 1rem;
}
h1 {
margin-top: 0;
}
.input-wrap {
margin-bottom: 1rem;
}
input#numberInput {
border: none;
border-bottom: 2px solid black;
font-size: 1rem;
}
input#numberInput:focus {
outline: none;
}
button {
background: #fceb5e;
border: 0;
border-radius: 0;
cursor: pointer;
font-size: 1rem;
-webkit-appearance: none;
padding: 0.25rem 1rem;
}
code#resultText {
background: rgba(0,0,0,0.25);
display: none;
padding: 0.25rem;
}
code#resultText.is-visible {
display: inline;
}
JavaScript
/**
* @author Jesse Rogers
* @fileoverview issue #147 of rendezvous with cassidoo
* Given a number n, return the number of 1s in the binary representation of n
*/
// add toBinary method to Number prototype
Number.prototype.toBinary = function() {
return (this >>> 0).toString(2).split('').map(x => +x);
}
function howManyOnes(n) {
if (typeof n !== 'number') {
throw new TypeError('Expected number for argument [num] but receieved ' + typeof n);
}
return n.toBinary().filter(x => x === 1).length;
}
const input = document.getElementById('numberInput');
const resultText = document.getElementById('resultText');
const button = document.getElementById('btn');
button.addEventListener('click', (event) => {
const number = input.value;
if (!isNaN(+number)) {
const result = howManyOnes(+number);
resultText.innerHTML = result;
resultText.classList.add('is-visible');
} else {
resultText.innerHTML = result;
resultText.classList.remove('is-visible');
}
});